﻿using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class Health : NetworkBehaviour {

    public int maxHp;

    [SyncVar(hook = "onChangeCurrentHp")]
    public int currentHp;
    // server to client direction only

    // Use this for initialization
    void Start() {
        currentHp = maxHp;
    }

    // Update is called once per frame
    void Update() {

    }

    public void takeDamage(int d) {
        if (!isServer) return; // run only in server side
        currentHp -= d;
        if (currentHp <= 0) {
            currentHp = maxHp;
            // called on the server, but invoked on the client
            RpcRespawn();
        }
    }

    public void onChangeCurrentHp(int hp) { // this is apply in client
        // if (isServer) Debug.Log("in server" + hp);
        // if (isClient) Debug.Log("in client" + hp);
        // in this scope, the currentHp may be a default value
        if (hp <= 0) {
            Debug.Log("dead");
            // TODO use a health bar
            // GetComponentInChildren<SporeSkin>().changeSkin(3);
        }
    }

    [ClientRpc]
    void RpcRespawn () {
        // GetComponentInChildren<SporeSkin>().changeSkin(2);
        if (isLocalPlayer) {
            transform.position = Vector3.zero;
            // GetComponentInChildren<SporeSkin>().changeSkin(0);
        }
    }
}
